package androidx.blogger;

import java.util.ArrayList;

import com.google.gwt.user.client.rpc.AsyncCallback;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.blogger.tasks.GetBlogCollectionTask;
import androidx.blogger.tasks.PostBlogEntryTask;
import androidx.gdata.blogger.Blog;
import androidx.gdata.blogger.BlogContent;
import androidx.gdata.blogger.BlogCollection;
import androidx.gdata.blogger.BlogEntry;
import androidx.gdata.blogger.BlogEntryBuilder;
import androidx.gdata.blogger.BloggerServer;
import androidx.util.ProgressIndicator;

public class MainActivity extends Activity {
  private BloggerServer server;
  
  private Spinner blogSelectionSpinner;
  private EditText entryTitleEditText;
  private EditText entryContentEditText;
  private Button postButton;
  private Button cancelButton;
  
  // Need to extend BlogCollection to include a toString that
  // return the title of the blog.
  // Should also change BlogCollection to Blog and Blog to BlogPost.
  private ArrayList<String> blogTitles;
  private ArrayAdapter<String> blogSpinnerAdapter;
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      blogSelectionSpinner = (Spinner)findViewById(R.id.blogSelectSpinner);
      entryTitleEditText = (EditText)findViewById(R.id.titleEditText);
      entryContentEditText = (EditText)findViewById(R.id.contentEditText);
      postButton = (Button)findViewById(R.id.postButton);
      postButton.setOnClickListener(postButtonClicked);
      cancelButton = (Button)findViewById(R.id.cancelButton);
      cancelButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
          clear();
        }        
      });
      
      blogTitles = new ArrayList<String>();
      
      blogSpinnerAdapter = new ArrayAdapter<String>(getApplicationContext(), 
          android.R.layout.simple_spinner_item,
          blogTitles);
      blogSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      blogSelectionSpinner.setAdapter(blogSpinnerAdapter);
    
      server = BloggerApplication.getInstance().getServer();
      if (server == null) {
        longMessage("No blogger server!");
        finish();
      }
      
      if (BloggerApplication.getInstance().getBlogCollection() == null)
      	GetBlogCollectionTask.execute(getProgressIndicator("Getting list of blogs"), feedCallback);
      else
        onReceiveBlogCollection(BloggerApplication.getInstance().getBlogCollection());
      Log.i("Blogger version 0.86");
  }
  
  private void clear() {
    entryTitleEditText.setText("");
    entryContentEditText.setText("");
  }
  
  OnClickListener postButtonClicked = new OnClickListener() {
    public void onClick(View arg0) {
      // Post the current blog post.
      String title = entryTitleEditText.getText().toString();
      String contentString = entryContentEditText.getText().toString();
      int index = blogSelectionSpinner.getSelectedItemPosition();
      if (index != Spinner.INVALID_POSITION) {
        Blog target = BloggerApplication.getInstance().getBlogCollection().getBlogs()[index];
        BlogEntryBuilder beb = new BlogEntryBuilder();
        boolean isDraft = false;
        BlogEntry entry = beb.setTitle(title).setBlogContent(new BlogContent("text", contentString)).setIsDraft(isDraft).build();
        PostBlogEntryTask.execute(getProgressIndicator("Posting to '" + target.getTitle() + "'"), 
          target, entry, blogPostCallback);
      }
    }
  };
  
  private void onReceiveBlogCollection(BlogCollection feed) {
    Log.i("Got list of blogs");
    // Populate the blog selection spinner.
    BloggerApplication.getInstance().setBlogCollection(feed);
    // TODO When Blogcollection is updated, don't need to update the blog title array.    
    blogTitles.clear();
    for (Blog b: feed.getBlogs()) {
      blogTitles.add(b.getTitle());
    }
    blogSpinnerAdapter.notifyDataSetChanged();
  }
  
  private void onReceiveBlogPostResult(Blog blog) {
    Log.i("Posted blog entry!");
    longMessage("Post successful!");
    clear();
    entryTitleEditText.requestFocus();
  }
  
  private AsyncCallback<Blog> blogPostCallback = new AsyncCallback<Blog>() {

		public void onSuccess(Blog result) {
			onReceiveBlogPostResult(result);
		}

		public void onFailure(Throwable t) {
			longMessage("Problem posting blog entry!");
		}
  };
  
  private AsyncCallback<BlogCollection> feedCallback = new AsyncCallback<BlogCollection>() {
		public void onSuccess(BlogCollection result) {
			onReceiveBlogCollection(result);
		}
		
		public void onFailure(Throwable t) {
			longMessage("Error getting blogs");
		}
  };
  
  private void shortMessage(String msg) {
    Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
    toast.show();
  }

  private void longMessage(String msg) {
    Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    toast.show();
  }
  
  private ProgressIndicator getProgressIndicator(String msg) {
  	progressMessage = msg;
  	return progressIndicator;
  }
  
  private ProgressDialog progressDialog;
  private String progressMessage;
  private ProgressIndicator progressIndicator = new ProgressIndicator() {
  	
		public void showProgressIndicator() {
			progressDialog = ProgressDialog.show(MainActivity.this, "Blogging", progressMessage);
		}
		public void hideProgressIndicator() {
			progressDialog.dismiss();
		}
  };
  
}
